package com.ibiaoke.order.service;

import com.ibiaoke.common.configs.AliPayConfigs;
import com.ibiaoke.common.configs.GlobalConfigs;
import com.ibiaoke.common.configs.GlobalConfigsKey;
import com.ibiaoke.common.consts.BusinessDef;
import com.ibiaoke.common.configs.AliPayConfigs;
import com.ibiaoke.common.configs.AppAliPayConfigs;
import com.ibiaoke.common.utils.AssertUtils;
import com.ibiaoke.common.utils.CashUtil;
import com.ibiaoke.common.utils.DateUtils;
import com.ibiaoke.common.utils.SmsUtil;
import com.ibiaoke.customer.consts.PayTypeConst;
import com.ibiaoke.customer.consts.TradeTypeConsts;
import com.ibiaoke.customer.entity.Customer;
import com.ibiaoke.customer.entity.PtOpenGroup;
import com.ibiaoke.customer.service.*;
import com.ibiaoke.order.consts.OrderStatusConst;
import com.ibiaoke.order.consts.PtOrderStatusConst;
import com.ibiaoke.order.entity.*;
import com.ibiaoke.pay.AppAliPay;
import com.ibiaoke.pay.AppWeChatPayClient;
import com.ibiaoke.pay.BkAliPayClient;
import com.ibiaoke.pay.BkWeChatPayClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;


@Service("/ptPayOrderService")
public class PtPayOrderServiceImpl implements PtPayOrderService{

    @Autowired
    private BkWeChatPayClient bkWeChatPayClient;

    @Autowired
    private PtOrderService ptOrderService;

    @Autowired
    private BkAliPayClient bkAliPayClient;

    @Autowired
    private AppWeChatPayClient appWeChatPayClient;

    @Autowired
    private AppAliPay appAliPay;

    @Autowired
    private DepositService depositService;

    @Autowired
    private DepositRecorderService depositRecorderService;

    @Autowired
    private OpenGroupService openGroupService;

    @Autowired
    private FightGroupService fightGroupService;

    @Autowired
    private CustomerService customerService;

    //微商城——微信支付
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, String> payOrderByWeChat(Integer orderId, String openId) {
            AssertUtils.notNull(orderId, "请选择订单");
            PtOrder ptOrder = ptOrderService.getPtOrderById(orderId);
            validate(ptOrder);
            String body = "让我来果源拼团订单：" + ptOrder.getPtOrderCode();
            String out_trade_no = ptOrder.getPtOrderCode();
            String total_fee = String.valueOf(CashUtil.getCent(ptOrder.getPrice()));
            String trade_type = "JSAPI";
            //String notify_url = "http://test.rangwolai.com.cn/weixin/wxPtPayNotify/Pt_PAY_ORDER.do";
            String notify_url = GlobalConfigs.getConfigure(GlobalConfigsKey.WeChat.Pt_NOTIFY_URL);
            notify_url = notify_url.replace("BUSINESS_TYPE", "Pt_PAY_ORDER");
            ptOrderService.checkBeforPay(orderId);
            return bkWeChatPayClient.wxPay(openId, body, out_trade_no, total_fee, trade_type, notify_url);
    }

    //App微信支付
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> payOrderByAppWeChat(Integer orderId, String ip) {
        AssertUtils.notNull(orderId, "请选择订单");
        PtOrder ptOrder = ptOrderService.getPtOrderById(orderId);
        validate(ptOrder);
        String body = "让我来果源订单：" + ptOrder.getPtOrderCode();
        String out_trade_no = ptOrder.getPtOrderCode();
        String total_fee = String.valueOf(CashUtil.getCent(ptOrder.getPrice()));
        String trade_type = "APP";
        String notify_url = "http://test.rangwolai.com.cn/weixin/wxPtPayNotify/WX_Pt_PAY_ORDER.do";
        return appWeChatPayClient.appWxPay(body,out_trade_no,total_fee,trade_type,notify_url,ip);
    }

    //预付款支付
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void payOrderByDepositPay(Integer orderId, String smsCode) {
            AssertUtils.notNull(orderId, "请选择支付订单");
            AssertUtils.notBlank(smsCode, "验证码不能为空");
            PtOrder ptOrder = ptOrderService.getPtOrderById(orderId);
            validate(ptOrder);
            Customer customer = customerService.getCustomerInfo(ptOrder.getUserId());
            SmsUtil.validateMobileCode(customer.getCustomerMobile(), smsCode);
            ptOrderService.checkBeforPay(orderId);
            //更改订单金额
            int i = depositService.payOrder(customer.getCustomerId(), ptOrder.getPrice());
            if (i > 0) {
                //增加更改金额日志
                depositRecorderService.insert(customer.getCustomerId(), PayTypeConst.DEPOSIT, ptOrder.getPtOrderCode(), TradeTypeConsts.CONSUME, ptOrder.getPrice());
                //更改订单状态
                ptOrderService.updateOrderStatus(ptOrder);
            }
    }

    //微商城——支付宝支付
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String payOrderByAliPay(Integer orderId) {
        AssertUtils.notNull(orderId, "请选择订单");
        PtOrder ptOrder = ptOrderService.getPtOrderById(orderId);
        validate(ptOrder);
        //商户订单号
        String out_trade_no = ptOrder.getPtOrderCode();
        String subject = "让我来果源订单:" + out_trade_no;
        String total_amount = ptOrder.getPrice() + "";
        String notify_url = AliPayConfigs.getPtNotifyURL();
        notify_url = notify_url.replace("BUSINESS_TYPE", "Ali_Pt_PAY_ORDER");
        String return_url = AliPayConfigs.getReturnURL();
        return bkAliPayClient.aliPay(out_trade_no, subject, total_amount, notify_url, return_url);
    }

    //App支付宝支付
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String payOrderByAppAliPay(Integer orderId) {
        AssertUtils.notNull(orderId, "请选择订单");
        PtOrder ptOrder = ptOrderService.getPtOrderById(orderId);
        validate(ptOrder);
        String total_amount = ptOrder.getPrice().toString();
        Map<String, Object> body = new Hashtable<String, Object>();
        body.put("out_trade_no", ptOrder.getPtOrderCode());
        body.put("subject", "让我来果源订单:" + ptOrder.getPtOrderCode());
        body.put("total_amount", total_amount);
        String notify_url = AliPayConfigs.getNotifyURL();
        notify_url = notify_url.replace("BUSINESS_TYPE", BusinessDef.PAY_ORDER);
        body.put("notify_url",notify_url);
        body.put("return_url",  AppAliPayConfigs.getReturnURL());
        return appAliPay.aliPay(total_amount,body);
    }

    //校验订单
    @Override
    public void validate(PtOrder ptOrder) {
        AssertUtils.notNull(ptOrder, "请选择支付订单");
        AssertUtils.requireEquals(ptOrder.getPtStatus(), PtOrderStatusConst.PAID , "订单已支付");
        AssertUtils.requireTrue(ptOrder.getPrice().compareTo(new BigDecimal("0.01")) >= 0,
                "支付金额不能小于0.01元");
        AssertUtils.requireTrue(ptOrder.getCreateTime().after(DateUtils.add(Calendar.HOUR,-1))
                ,"订单超时，不能支付");
    }
}
